const express = require("express");
const app = express();
const session = require("express-session");
const MongoStore = require("connect-mongo")(session);

//设置session
app.use(session({
    name: "session_id", //保存在本地cookie的一个名字 默认connect.sid  可以不设置
    secret: "mySign", //session签名
    resave: false, //不强制保存session
    saveUninitialized: true, //强制将未初始化的session存储
    rolling: true, //在每次请求时强行设置cookie
    cookie: {
        maxAge: 30 * 60 * 1000 //过期时间
    },
    store: new MongoStore({
        url: "mongodb://127.0.0.1:32768/user",
        touchAfter: 24 * 3600 //24小时内只更新一次会话，不管有多少请求(除了在会话数据上更改某些内容的除外)
    })
}));

app.get("/", (req, res) => {
    //获取session
    let userInfo = req.session.userInfo;
    if (userInfo) {
        res.send("你好" + userInfo + "，欢迎回来！");
    } else {
        res.send("未登录");
    }
});

app.get("/login", (req, res) => {
    req.session.userInfo = "张三";
    res.send('登录成功');
});

app.get("/loginOut", (req, res) => {
    req.session.destroy(err => {
        res.send('退出登录成功');
    });
});

app.listen(8080);